import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Events } from '@core/services/events/Events';
import * as distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
import { ToDoItem } from '@shared/todo/interface';
import * as CryptoJS from 'crypto-js';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { UserAuthService } from '@core/services/user-auth.service';
import { MenuService } from '@core';
import {FormService} from "@core/services/form.service";
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'pad-form',
  templateUrl: './pad-form.component.html',
  styleUrls: ['./pad-form.component.scss'],
})
export class PadFormComponent implements OnInit {
  @Output() select = new EventEmitter<any>();
  data: any[] = [];
  prefixCls = 'apes-todo';
  contentData: any[] = [];
  userId: string;
  sessionId: string;
  posts = []; // 岗位列表
  currentPostName: string;

  constructor(private router: Router,
              private apiService: ApiService,
              protected events: Events,
              public msg: ApesMessageService,
              private routeInfo: ActivatedRoute,
              protected rs: ReuseTabService,
              private userAuthService: UserAuthService,
              private menuService: MenuService,
              private formService: FormService) {
  }

  ngOnInit() {
    //  解密
    this.routeInfo.queryParams.subscribe((params: Params) => {
      let value = CryptoJS.enc.Base64.parse(params['value']);
      value = value.toString(CryptoJS.enc.Utf8);
      this.userId = value;
    });
    this.goLogin(this.userId);

    this.apiService.post('wf.getTasksForCustomComplain', { 'sessionId': this.sessionId,
      'body': JSON.stringify({ 'userId': this.userId }) })
      .subscribe((items) => {
        this.data = items;
      });
  }

  goLogin(userId: string) {
    const data = { 'userId': userId };
    if (userId) {
    this.apiService.post('aut.user.loginIgnorePassword', { 'body': JSON.stringify(data) })
      .subscribe((items) => {
        const resultData = items.user;
        resultData['post'] = resultData.posts[0];
        this.sessionId = items.sessionId;
        const userInfo = { 'token': items.sessionId, 'userAccount': resultData };
        this.posts = userInfo.userAccount.posts;
        this.currentPostName = userInfo.userAccount.post.name;
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
      });
    } else {
      this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
    }
  }


  onClick(item: ToDoItem) {
    this.formService.navigateToForm(item);
  }

  getDataContent(metadata) {
    if (metadata) {
      this.showContentData(metadata);
      return true;
    } else {
      return false;
    }
  }

  showContentData(data: any) {
    this.contentData = [];
    for (const key in  data) {
      this.contentData.push(key + ':' + data[key]);
    }
  }

  getDateTime(datetime) {
    const date = new Date(datetime);
    return distanceInWordsToNow(date, {
      locale: (window as any).__locale__,
    });
  }

  changePost(postId: string) {
    // 检查数据的正确性
    let currentPost = this.posts.filter((post) => post.id == postId);
    if (currentPost.length === 0)
      return;

    // 检查是否改变 post
    let userInfo = this.userAuthService.getUserInfoObj();
    let currentPostInfo = userInfo.userAccount.post;
    if ( postId === currentPostInfo.id )
      return;


    // 重新请求后端刷新菜单
    this.apiService.post('aut.user.bindPost', {'body': JSON.stringify({post: {id : postId}})}).subscribe(
      (body) => {
        this.menuService.clear();

        if( body ){
          this.menuService.add(body);
        }

        // 将当前的数据存入 storage 中
        userInfo.userAccount.post = currentPost[0];
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));

        this.currentPostName = currentPost[0].name;
      });
  }
}
